package com.zf.yichat.service.config;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zf.yichat.dto.UltragroupAdminUserDto;
import com.zf.yichat.dto.UltragroupMemberUserDto;
import com.zf.yichat.mapper.*;
import com.zf.yichat.model.MessageUltragroup;
import com.zf.yichat.model.MessageUltragroupAdminUser;
import com.zf.yichat.model.UserJoinUltragroup;
import com.zf.yichat.service.UserService;
import com.zf.yichat.utils.common.DateUtils;
import com.zf.yichat.utils.common.FsConst;
import com.zf.yichat.utils.common.N3d;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wu
 * 超级群服务
 */
@Component
public class UltragroupService {

    // 注入配置文件中的融云API配置
    @Value("${rongcloud.key}")
    private String appKey;

    @Value("${rongcloud.secret}")
    private String appSecret;

    @Autowired
    private RongCloudApplication rongCloudApplication;

    @Autowired
    private MessageUltragroupMapper messageUltragroupMapper;

    @Autowired
    private MessageUltragroupAdminUserMapper ultragroupAdminUserMapper;

    @Autowired
    private UserJoinUltragroupMapper userJoinUltragroupMapper;


    @Autowired
    private UserJoinUltragroupApplyMapper userJoinUltragroupApplyMapper;

    @Autowired
    private UserService userService;


    public UltragroupService() {

    }

    /**
     * 创建超级群
     * @param userId
     * @param groupName
     * @param avatar
     * @return
     * @throws Exception
     */
    @Transactional
    public Integer createUltragroup(Long userId, String groupName, String avatar, String approval) throws Exception {

        // 创建超级群-Id 以100开始 后7位为随机数
        String ultragroupId = "100";

        String numbers = RandomUtil.randomNumbers(7);
        ultragroupId = ultragroupId + numbers;

        Long ultragroupIdL = Long.valueOf(ultragroupId);
        String encodeGroupId = N3d.encode(ultragroupIdL);
        String encodeUserId = N3d.encode(userId);

        HttpPost httpPostCreate = rongCloudApplication.imConstructor("ultragroup/create");
        List<NameValuePair> paramsCreate = new ArrayList<>();
        paramsCreate.add(new BasicNameValuePair("userId", encodeUserId));
        paramsCreate.add(new BasicNameValuePair("groupId", encodeGroupId));
        paramsCreate.add(new BasicNameValuePair("groupName", groupName));
        httpPostCreate.setEntity(new UrlEncodedFormEntity(paramsCreate, StandardCharsets.UTF_8));

        String responseCreate = rongCloudApplication.executeReq(httpPostCreate);
        // 解析响应数据
        JSONObject jsonObjectCreate = JSON.parseObject(responseCreate);
        String keepaliveCodeCreate = jsonObjectCreate.getString("code");

        if ("200".equals(keepaliveCodeCreate)) {
                // 将群主加入白名单
                HttpPost httpPost = rongCloudApplication.imConstructor("ultragroup/banned/whitelist/add");
                // 设置请求消息体参数
                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("groupId", encodeGroupId));
                params.add(new BasicNameValuePair("userIds", encodeUserId));
                httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

                String response = rongCloudApplication.executeReq(httpPost);
                // 解析响应数据
                JSONObject jsonObject = JSON.parseObject(response);
                String whitelistCode = jsonObject.getString("code");

                // 管理员设置成功后保存管理员与超级群的数据到数据库
                if ("200".equals(whitelistCode)) {
                    // 创建超级群成功后存储到数据库
                    MessageUltragroup ultragroup = new MessageUltragroup();
                    ultragroup.setUltragroupId(encodeGroupId);// 密文groupId
                    ultragroup.setUltragroupIdNum(ultragroupIdL);
                    ultragroup.setUltragroupName(groupName);
                    ultragroup.setApproval(approval);
                    ultragroup.setCreateTime(new Date());
                    if (StringUtils.isNotBlank(avatar)) {
                        ultragroup.setAvatar(avatar);
                    }
                    ultragroup.setStatus(FsConst.Status.EFFECT);
                    messageUltragroupMapper.insert(ultragroup);

                    // 加入到超级群成员列表
                    UserJoinUltragroup joinUltragroup = new UserJoinUltragroup();
                    joinUltragroup.setUltragroupId(ultragroupId);
                    joinUltragroup.setUserId(userId);
                    // 设置为群主
                    joinUltragroup.setLevel(UserJoinUltragroup.LEVEL_OWNER);
                    joinUltragroup.setCreateTime(new Date());
                    userJoinUltragroupMapper.insert(joinUltragroup);
                }

        }else {
            return FsConst.Status.EXCEED;
        }
        // 处理 result 中的信息
        return 200;
    }


    /**
     * 查询超级群列表
     * @return
     * @throws Exception
     */
    public List<MessageUltragroup> getUltragroupList() throws Exception {
        // 存放超级群列表
        List<MessageUltragroup> survival = new ArrayList<>();

        // 查询所有创建的聊天室
        List<MessageUltragroup> ultragroupList = messageUltragroupMapper.selectAll();
        for (MessageUltragroup messageUltragroup : ultragroupList) {
            Integer status = messageUltragroup.getStatus();
            if (MessageUltragroup.STATUS_0 == status){
                Date createTime = messageUltragroup.getCreateTime();
                DateUtils.formatDate(createTime);
                messageUltragroup.setCreateTime(createTime);

                survival.add(messageUltragroup);
            }
        }
        return survival;
    }


    /**
     * 设置聊天室管理员
     * @param ultragroupId 超级群ID
     * @param userIds 要添加到白名单的人员
     * @return
     * @throws Exception
     */
    public Integer UltragroupAdmin(String ultragroupId, String userIds) throws Exception {

        String[] split = userIds.split("\\|");

        // 首先加入超级群
        if (joinUltragroup(ultragroupId, userIds)) {
            // 添加到超级群禁言白名单
            HttpPost httpPost = rongCloudApplication.imConstructor("ultragroup/banned/whitelist/add");

            // 设置请求消息体参数
            String encodeUltragroupId = N3d.encode(Long.valueOf(ultragroupId));
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("groupId", encodeUltragroupId));

            for (String whiteId : split) {
                String encodeWhiteId = N3d.encode(Long.valueOf(whiteId));
                params.add(new BasicNameValuePair("userIds", encodeWhiteId));
            }

            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            String response = rongCloudApplication.executeReq(httpPost);
            // 解析响应数据
            JSONObject jsonObject = JSON.parseObject(response);
            String whitelistCode = jsonObject.getString("code");

            // 管理员设置成功后保存管理员与超级群的数据到数据库
            if ("200".equals(whitelistCode)) {
                MessageUltragroupAdminUser adminUser = new MessageUltragroupAdminUser();
                adminUser.setUltragroupId(ultragroupId);
                for (int i = 0; i < split.length; i++) {
                    String adminUserId = split[i];
                    adminUser.setUserId(Long.valueOf(adminUserId));
                    ultragroupAdminUserMapper.insert(adminUser);


                    // 查询在超级群人员列表中是否存在该用户
                    UserJoinUltragroup ultragroup = userJoinUltragroupMapper.queryUserInUltragroup(Long.valueOf(adminUserId), ultragroupId);
                    if(null == ultragroup){
                        // 加入到超级群成员列表
                        UserJoinUltragroup joinUltragroup = new UserJoinUltragroup();
                        joinUltragroup.setUltragroupId(ultragroupId);
                        joinUltragroup.setUserId(Long.valueOf(adminUserId));
                        // 设置为管理员
                        joinUltragroup.setLevel(UserJoinUltragroup.LEVEL_ADMIN);
                        joinUltragroup.setCreateTime(new Date());
                        userJoinUltragroupMapper.insert(joinUltragroup);
                    }else {
                        UserJoinUltragroup joinUltragroup = new UserJoinUltragroup();
                        joinUltragroup.setId(ultragroup.getId());
                        joinUltragroup.setLevel(UserJoinUltragroup.LEVEL_ADMIN);
                        userJoinUltragroupMapper.updateByPrimaryKeySelective(joinUltragroup);
                    }

                }
                return FsConst.Status.IS_OK;
            }
        }
        return FsConst.Status.EXCEED;
    }

    @Transactional
    public FsResponse ultragroupApply(String ultragroupId, String userId, String status) throws Exception{
        // 更新审批表状态
       int i = userJoinUltragroupApplyMapper.updateStatusByParam(ultragroupId, userId, status);

       // 审核通过 新增聊天室成员信息
       if (UserJoinUltragroup.STATUS_APPROVED.equals(status) && i > 0) {

           UserJoinUltragroup ultragroup = userJoinUltragroupMapper.queryUserInUltragroup(Long.valueOf(userId), ultragroupId);
           if (null == ultragroup) {

               if (!userService.realValidStatus(Long.valueOf(userId))) {
                   return FsResponseGen.failMsg("请先实名认证");
               }

               if (joinUltragroup(ultragroupId, userId)) {
                   // 增加群成员信息
                   UserJoinUltragroup joinUltragroup = new UserJoinUltragroup();
                   joinUltragroup.setUserId(Long.valueOf(userId));
                   joinUltragroup.setUltragroupId(ultragroupId);
                   joinUltragroup.setLevel(UserJoinUltragroup.LEVEL_MEMBER);
                   joinUltragroup.setCreateTime(new Date());
                   return FsResponseGen.successData(userJoinUltragroupMapper.insertSelective(joinUltragroup));
               }

           }
       }
        return FsResponseGen.successData(i);
    }

    /**
     * 加入超级群接口
     * @param ultragroupId
     * @param userId
     * @return
     * @throws Exception
     */
    public boolean joinUltragroup(String ultragroupId, String userId) throws Exception{
        // 融云加入超级群
        HttpPost httpPost = rongCloudApplication.imConstructor("ultragroup/join");
        // 设置请求消息体参数
        String encodeUltragroupId = N3d.encode(Long.valueOf(ultragroupId));
        Long aLongUserId = Long.valueOf(userId);
        String encodeUserId = N3d.encode(aLongUserId);

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("userId", encodeUserId));
        params.add(new BasicNameValuePair("groupId", encodeUltragroupId));

        httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
        String response = rongCloudApplication.executeReq(httpPost);
        // 解析响应数据
        JSONObject jsonObject = JSON.parseObject(response);
        String whitelistCode = jsonObject.getString("code");

        return "200".equals(whitelistCode);
    }

    /**
     * 更新超级群信息
     * @param ultragroupId
     * @param status
     * @param ultragroupName
     * @throws Exception
     */
    public void updateUltragroup(Long ultragroupId, String status, String ultragroupName, String avatar, String approval) throws Exception{
        if (StringUtils.isNotBlank(status)) {
            messageUltragroupMapper.ultragroupUpdateStatus(ultragroupId, status);
        }
        else if (StringUtils.isNotBlank(ultragroupName)) {
            // 融云刷新超级群信息
            HttpPost httpPost = rongCloudApplication.imConstructor("ultragroup/refresh");

            // 设置请求消息体参数
            String encodeUltragroupId = N3d.encode(Long.valueOf(ultragroupId));
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("groupId", encodeUltragroupId));
            params.add(new BasicNameValuePair("groupName", ultragroupName));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
            String response = rongCloudApplication.executeReq(httpPost);
            // 解析响应数据
            JSONObject jsonObject = JSON.parseObject(response);
            String whitelistCode = jsonObject.getString("code");
            if ("200".equals(whitelistCode)) {
                messageUltragroupMapper.ultragroupUpdateChatroom(ultragroupId, ultragroupName, avatar, approval);
            }
        }
    }

    /**
     * 查询超级群管理员
     * @param ultragroupId
     * @param userId
     * @param nick
     * @param mobile
     * @param realName
     * @return
     */
    public List<UltragroupAdminUserDto> queryUltragroupAdmin(String ultragroupId, String userId, String nick, String mobile, String realName) {
        return ultragroupAdminUserMapper.queryUltragroupAdmin(ultragroupId, userId, nick, mobile, realName);
    }


    /**
     *  删除超级群管理员
     * @param ultragroupId
     * @param userId
     * @return
     * @throws Exception
     */
    public int deleteUltragroupAdmin(String ultragroupId, String userId) throws Exception {

        // 移出超级群全体禁言白名单
        if (delwhitelist(ultragroupId, userId)) {
            // 退出超级群
            boolean quitUltragroup = quitUltragroup(ultragroupId, userId);
            if (quitUltragroup) {
                userJoinUltragroupMapper.deleteUltragroupMember(ultragroupId, userId);
                // 删除本地数据库中的管理员信息
                return ultragroupAdminUserMapper.deleteUltragroupAdmin(ultragroupId, userId);
            }
        }
        return 0;
    }

    /**
     * 融云-移出超级群全体禁言白名单
     * @param ultragroupId
     * @param userId
     * @return
     */
    public boolean delwhitelist(String ultragroupId, String userId) throws Exception{
        // 调取移出超级群全体禁言白名单接口
        HttpPost httpPost = rongCloudApplication.imConstructor("ultragroup/banned/whitelist/del");

        // 设置请求消息体参数
        String encodeGroupIdId = N3d.encode(Long.valueOf(ultragroupId));
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("groupId", encodeGroupIdId));

        String encodeWhiteId = N3d.encode(Long.valueOf(userId));
        params.add(new BasicNameValuePair("userIds", encodeWhiteId));

        httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
        String response = rongCloudApplication.executeReq(httpPost);
        // 解析响应数据
        JSONObject jsonObject = JSON.parseObject(response);
        String whitelistCode = jsonObject.getString("code");
        return "200".equals(whitelistCode);
    }

    /**
     * 查询超级群用户列表
     * @param ultragroupId
     * @param userId
     * @param nick
     * @param mobile
     * @param realName
     * @return
     */
    public List<UltragroupMemberUserDto> queryUltragroupMember(String ultragroupId, String userId, String nick, String mobile, String realName) {
        return userJoinUltragroupMapper.queryUltragroupMember(ultragroupId, userId, nick, mobile, realName);
    }

    /**
     * 删除超级群用户
     * @param ultragroupId
     * @param userId
     * @return
     */
    public int deleteUltragroupMember(String ultragroupId, String userId) throws Exception{
        // 退出超级群
        boolean quitUltragroup = quitUltragroup(ultragroupId, userId);
        if (quitUltragroup) {
            return userJoinUltragroupMapper.deleteUltragroupMember(ultragroupId, userId);
        }
        return 0;
    }

    /**
     * 融云-退出超级群
     * @param ultragroupId
     * @param userId
     * @return
     */
    public boolean quitUltragroup(String ultragroupId, String userId) throws Exception{
        // 调取退出超级群接口
        HttpPost httpPost = rongCloudApplication.imConstructor("ultragroup/quit");

        // 设置请求消息体参数
        String encodeGroupIdId = N3d.encode(Long.valueOf(ultragroupId));
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("groupId", encodeGroupIdId));

        String encodeWhiteId = N3d.encode(Long.valueOf(userId));
        params.add(new BasicNameValuePair("userId", encodeWhiteId));

        httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
        String response = rongCloudApplication.executeReq(httpPost);
        // 解析响应数据
        JSONObject jsonObject = JSON.parseObject(response);
        String whitelistCode = jsonObject.getString("code");
        return "200".equals(whitelistCode);
    }

    public void deleteUltragroup(Long id, String ultragroupId) throws Exception {

        // 调用融云解散超级群接口
        boolean disUltragrooup = disUltragrooup(ultragroupId);
        if (disUltragrooup) {
            // 删除本地数据
            messageUltragroupMapper.deleteByPrimaryKey(id);
        }
    }

    /**
     * 解散超级群
     * @param ultragroupId
     * @return
     */
    public boolean disUltragrooup(String ultragroupId) throws Exception{
        // 调取退出超级群接口
        HttpPost httpPost = rongCloudApplication.imConstructor("ultragroup/dis");

        // 设置请求消息体参数
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("groupId", ultragroupId));

        httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
        String response = rongCloudApplication.executeReq(httpPost);
        // 解析响应数据
        JSONObject jsonObject = JSON.parseObject(response);
        String whitelistCode = jsonObject.getString("code");
        return "200".equals(whitelistCode);
    }

    public List<MessageUltragroup> queryJoinUltragroup(Long userId) {
        return messageUltragroupMapper.queryJoinUltragroup(userId);
    }
}
